#include "threadpool.h"
bool isExit(const char* filename,const char* vir_path){
       DIR* pdir=opendir(vir_path);
       struct dirent* pdirent;
       while((pdirent=readdir(pdir))!=NULL){
           if(strcmp(pdirent->d_name,filename)==0){
               return 1;
           }
       }
       return 0;
}
int recvN(int netfd, void* buf, int length)
{
    int total = 0;      // 已经recv的字节数
    char* p = (char*)buf;
    while(total < length) 
    {
        int ret = recv(netfd, p + total, length - total, 0);
        if(ret == 0) 
        {
            return -1;
        }
        total += ret;
    }

    return 0;
}
int getFile(char* filename,int netfd,char* vir_path){
    if(isExit(filename,vir_path)!=1){
        return -1;
    }
//文件存在    
    char filepath[1024];
    strcpy(filepath,vir_path);
    strcat(filepath,"/");
    strcat(filepath,filename);

    train_t train;
    bzero(&train,sizeof(train));

    off_t offset;
    int length;
    recvN(netfd,&length,sizeof(length));
    recvN(netfd,&offset,length);
    int fd=open(filepath,O_RDWR);
    struct stat statbuf;
    fstat(fd,&statbuf);
    close(fd);
    if(statbuf.st_size>=BIG_FILE_SIZE){
        printf("big file\n");
        int ret = mmapSendFile(filename,netfd,offset);
        if(ret!=0){
            return -1;
        }
    }else{
        printf("small file\n");
        fd=open(filepath,O_RDWR);
        lseek(fd,offset,SEEK_SET);
    }
    while(1){
        bzero(&train,sizeof(train));
        train.length=read(fd,train.data,sizeof(train.data));
        send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);
        if(train.length==0){
            break;
        }
    }
   close(fd);
    return 0;

}
int putFile(char *filename,int netfd,char* vit_path){
    char filepath[1024];
    strcpy(filepath,vit_path);
    strcat(filepath,"/");
    strcat(filepath,filename);
    int fd=open(filepath,O_RDWR|O_CREAT|O_TRUNC,0666);
    char buf[1024]={0};
    int length;
    while(1){
        recvN(netfd,&length,sizeof(length));
        if(length==0){
            break;
        }
        bzero(buf,sizeof(buf));
        recvN(netfd,buf,length);
        write(fd,buf,length);
    }
    close(fd);
    return 0;
}




















